package com.tydic.baselibrary.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import androidx.annotation.NonNull;
import android.text.TextUtils;

import java.util.List;


/**
 * @author 依风听雨
 * @version 创建时间：2017/11/16 14:00
 */

public class AppUtils {

    /**
     * @param context     activity
     * @param versionName 版本号
     * @return true 有新版本
     */
    public static boolean checkVersion(@NonNull Context context, @NonNull String versionName) {
        if (TextUtils.isEmpty(versionName) || getAppVersionName(context).equals(versionName)) {
            return false;
        }
        String[] newVersion = versionName.split("\\.");
        String[] currentVersion = getAppVersionName(context).split("\\.");
        for (int i = 0; i < Math.min(newVersion.length, currentVersion.length); i++) {
            int diff = Integer.parseInt(newVersion[i]) - Integer.parseInt(currentVersion[i]);
            if (diff > 0) {
                return true;
            } else if (diff < 0) {
                return false;
            }
        }
        return false;
    }

    /**
     * get app version code
     *
     * @param context
     * @return
     */
    public static String getAppVersionName(Context context) {
        if (context != null) {
            PackageManager pm = context.getPackageManager();
            if (pm != null) {
                PackageInfo pi;
                try {
                    pi = pm.getPackageInfo(context.getPackageName(), 0);
                    if (pi != null) {
                        return pi.versionName;
                    }
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return "1.0.0";
    }

    public static boolean checkAppInstalled( Context context, String pkgName) {
        if (pkgName== null || pkgName.isEmpty()) {
            return false;
        }
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> info = packageManager.getInstalledPackages(0);
        if(info == null || info.isEmpty())
            return false;
        for ( int i = 0; i < info.size(); i++ ) {
            if(pkgName.equals(info.get(i).packageName)) {
                return true;
            }
        }
        return false;
    }

}
